package com.hy.util;

import org.springframework.http.*;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

public class AliyunRealNameAuthUtils {

    // 阿里云接口配置
    private static final String APP_KEY = "204875378";
    private static final String APP_SECRET = "oQ80QIWRwREeYWz2fvUp6iCrEzjaViKb";
    private static final String APP_CODE = "ed4fedfd2f6a41929a70c48e5a7509fa";
    private static final String API_URL = "https://idenauthen.market.alicloudapi.com/idenAuthentication";

    private static final RestTemplate restTemplate = new RestTemplate();

    /**
     * 发起实名认证请求
     * @param realName 姓名
     * @param idCard 身份证号
     * @return 认证结果（包含success、message、data等字段）
     */
    public static Map<String, Object> authenticate(String realName, String idCard) {
        try {
            // 构建请求参数
            Map<String, String> requestBody = new HashMap<>();
            requestBody.put("name", realName);    // 姓名参数（需与接口文档一致）
            requestBody.put("idNo", idCard);        // 身份证号参数（需与接口文档一致）



            // 构建请求头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
            headers.add("Authorization", "APPCODE " + APP_CODE);  // 使用AppCode认证

            // 转换请求体为FormData格式
            MultiValueMap<String, String> formData = new LinkedMultiValueMap<>();
            requestBody.forEach(formData::add);
            HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(formData, headers);

            // 发起POST请求
            ResponseEntity<Map> response = restTemplate.exchange(
                    API_URL,
                    HttpMethod.POST,
                    requestEntity,
                    Map.class
            );

            // 处理响应结果
            if (response.getStatusCode() == HttpStatus.OK) {
                Map<String, Object> result = response.getBody();
                // 这里可根据阿里云实际返回结构添加业务逻辑（如解析data中的详细信息）
                return result;
            } else {
                return buildErrorResult("接口请求失败，HTTP状态码：" + response.getStatusCodeValue());
            }
        } catch (Exception e) {
            e.printStackTrace();
            return buildErrorResult("认证请求异常：" + e.getMessage());
        }
    }

    /**
     * 构建错误结果
     */
    private static Map<String, Object> buildErrorResult(String message) {
        Map<String, Object> result = new HashMap<>();
        result.put("success", false);
        result.put("message", message);
        return result;
    }

    // 使用示例（可在Spring Boot Service中调用）
    public static void main(String[] args) {
        Map<String, Object> result = authenticate("张三", "110101198001011234");
        System.out.println("认证结果：" + result);
    }
}
